﻿using CapHttp.Core;
using CapHttp.Demo.Shared.Events;
using CapHttp.Producer.Api.Entities;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;

namespace CapHttp.Producer.Api.Controllers;

[ApiController]
[Route("[controller]/[action]")]
public class TestController : ControllerBase
{
    private readonly IDistributedEventPublisher _eventPublisher;
    private readonly ISqlSugarClient _db;

    public TestController(IDistributedEventPublisher eventPublisher, ISqlSugarClient db)
    {
        _eventPublisher = eventPublisher;
        _db = db;
    }

    [HttpPost]
    public async Task Test1(int id, string name)
    {
        await _eventPublisher.PublishAsync(new Event1(id, name));
    }

    [HttpPost]
    public async Task Test2(Event2 event2)
    {
        await _eventPublisher.PublishAsync(event2);
    }

    [HttpPost]
    public Guid CreateUser(CreateUserDto dto)
    {
        using var transaction = _db.BeginCapTransaction(_eventPublisher, true);
        var appUser = new AppUser
        {
            Id = Guid.NewGuid(),
            Name = dto.Name,
            Age = dto.Age,
            Address = dto.Address,
        };
        _db.Insertable(appUser).ExecuteCommand();
        _eventPublisher.Publish(new UserCreatedEvent(appUser.Id));
            
        return appUser.Id;
    }

    [HttpPost]
    public Guid WithException()
    {
        using var transaction = _db.BeginCapTransaction(_eventPublisher, false);
        var number = Random.Shared.Next(1, 200);
        var appUser = new AppUser
        {
            Id = Guid.NewGuid(),
            Name = "test name " + number,
            Age = number,
            Address = "test address " + number,
        };
        _db.Insertable(appUser).ExecuteCommand();
        _eventPublisher.Publish(new UserCreatedEvent(appUser.Id));
        if (appUser.Age % 2 == 0)
            throw new Exception($"NUMBER is {number}");
        
        transaction.Commit();

        return appUser.Id;
    }
}

public class CreateUserDto
{
    public string Name { get; set; }
    public int Age { get; set; }
    public string? Address { get; set; }
}